//-----------------------------------------------------------------------
// <copyright file="SubscriptionWireupStrategy.cs" company="iron9light">
//      Copyright (c) iron9light. All rights reserved.
// </copyright>
// <author>iron9light</author>
//-----------------------------------------------------------------------

namespace EventBrokerExtension
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;

    using EventBroker;

    using Microsoft.Practices.ObjectBuilder2;

    public class SubscriptionWireupStrategy : EventBrokerStrategyBase
    {
        public override void PreBuildUp(IBuilderContext context)
        {
            if (context.Existing != null)
            {
                ISubscriptionSelectorPolicy policy = context.Policies.Get<ISubscriptionSelectorPolicy>(context.BuildKey);

                if (policy != null)
                {
                    IEventBroker broker = GetBroker(context);

                    foreach (SubscriptionInfo subscriptionInfo in policy.GetSubscriptionInfos(context))
                    {
                        broker.RegisterSubscription(
                                subscriptionInfo.EventTopic,
                                context.Existing,
                                subscriptionInfo.Method.Name,
                                GetParameterTypes(subscriptionInfo.Method));
                    }
                }
            }
        }

        public override void PreTearDown(IBuilderContext context)
        {
            if (context.Existing != null)
            {
                IEventBroker broker = GetBroker(context);
                broker.UnregisterSubscriber(context.Existing);
            }
        }

        /// <summary>
        /// Gets the parameter types.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <returns>The parameter types.</returns>
        private static Type[] GetParameterTypes(MethodInfo method)
        {
            List<Type> types = new List<Type>();
            foreach (ParameterInfo parameterInfo in method.GetParameters())
            {
                types.Add(parameterInfo.ParameterType);
            }

            return types.ToArray();
        }
    }
}